package sample.controller.todo;

import java.util.List;
import java.util.logging.Logger;
import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;
import org.slim3.datastore.Datastore;

import sample.controller.meta.CategoryMeta;
import sample.controller.meta.TodoMeta;
import sample.controller.model.Todo;

public class IndexController extends Controller {

    @SuppressWarnings("unused")
    private static final Logger logger =
        Logger.getLogger(IndexController.class.getName());

    private static final Integer PAGE_COUNT = 5;

    @Override
    public Navigation run() {
        TodoMeta tm = new TodoMeta();
        CategoryMeta cm = new CategoryMeta();

        // 総件数(このメソッドが返す結果件数は最大1000なのでそれを越える場合、
        // 別の方法を考える
        // low-level APIのPreparedQuery#countEntitiesと同じ
        Integer count = Datastore.query(tm).countQuickly();

        // ページング処理
        Integer page = asInteger("page");
        if (page == null || page < 0)
            page = 0;
        if (page != null && page > 0 && page * PAGE_COUNT >= count)
            page = page - 1;
        Integer offset = page * PAGE_COUNT;

        requestScope("count", count);
        requestScope("page", page);

        List<Todo> list =
            Datastore.query(tm)
                .sort(tm.done.asc)
                .offset(offset)
                .limit(PAGE_COUNT).asList();
        for (Todo t : list) {
            t.setCategory(Datastore.get(cm, t.getKey().getParent()));
        }
        requestScope("list", list);
        return forward("index.jsp");
    }
}
